package com.can.Service.Impl;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch.core.SearchResponse;
import co.elastic.clients.json.jackson.JacksonJsonpMapper;
import co.elastic.clients.transport.ElasticsearchTransport;
import co.elastic.clients.transport.rest_client.RestClientTransport;
import com.can.Client.UserClient;
import com.can.Mapper.GameStoreMapper;
import com.can.Service.DbTccService;
import com.can.Service.EsService;
import com.can.Service.EsTccService;
import com.can.domain.po.Game;
import com.can.domain.vo.GameStoreVo;
import io.seata.rm.tcc.api.BusinessActionContext;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.RequiredArgsConstructor;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.List;

@Service
@RequiredArgsConstructor
public class GameStoreServiceImpl implements com.can.Service.GameStoreService {
    @Autowired
    GameStoreMapper gameMapper;

    @Value("${file.upload-dir}")
    String uploadDir;
    private final UserClient userClient;
    private final RabbitTemplate rabbitTemplate;

    @Autowired
    EsService esService;

    @Autowired
    EsTccService esTccService;
    @Autowired
    DbTccService dbTccService;

    @Override
    public GameStoreVo GetAllGames() {
        try{
            List<Game> res= gameMapper. selectList(null);
            return new GameStoreVo<>(200,"查询成功",res);
        }catch (Exception e){
            e.printStackTrace();
            return new GameStoreVo<>(500,"查询失败","");
        }

    }

    @Override
    public GameStoreVo GetGamedetail(int id) {
        try{
            Game res= gameMapper.GetGamedetailBYId(id);
            System.out.println(res);
            return new GameStoreVo<>(200,"查询成功",res);
        }catch (Exception e){
            e.printStackTrace();
            return new GameStoreVo<>(500,"查询失败","");
        }
    }

    @Override
    public GameStoreVo SearchGame(String name) throws IOException {
            return esService.SearchGame(name);

    }

    @Transactional
    @Override
    public GameStoreVo deleteGameById(int id) {
        try {
            gameMapper.deleteById(id);
            esService.deleteGameDocById(id);

            String fileName = id-1 + ".jpg"; // 获取上传文件的原始文件名
             Path targetPath = Paths.get(uploadDir + fileName);
            System.out.println("删除图片目标:"+targetPath);
                Files.delete(targetPath);
                System.out.println("图片删除成功！");}
        catch (IOException e) {
                System.err.println("图片删除失败：" + e.getMessage());
                return new GameStoreVo<>(500,"删除失败",null);
            }
        catch (Exception e){
            System.out.println(e.getMessage());
            return new GameStoreVo<>(500,"删除失败",null);
        }
        return new GameStoreVo<>(200,"删除成功",null);
    }

    @GlobalTransactional
    @Override
    public GameStoreVo addGame(int userId,String title,String content,MultipartFile file) {

         try {
//            插入到数据库
            Game game = new Game();
            game.setGamename(title);
            game.setContent(content);
            gameMapper.insert(game);

            // 2. 同步更新ES（若失败，Seata会回滚数据库）
            esService.addGameDoc(game);
//             //             发送消息队列
//             rabbitTemplate.convertAndSend("exp.fanout", "", userId);
             if (userClient.jia3(userId).getState()!=200){
                throw new RuntimeException("加3失败！");
        }

//            保存图片
            int gameId = game.getId()-1; // 确保Game实体类有id字段和getter方法
             System.out.println("插入的id："+gameId);
            if (gameId == 0) {
            return new GameStoreVo<>(500, "插入游戏记录失败", null);
        }
            String fileName = gameId + ".jpg"; // 获取上传文件的原始文件名
            String filePath = uploadDir + fileName;
             System.out.println(filePath);
            Path targetPath = Paths.get(filePath);
            Files.copy(file.getInputStream(), targetPath, StandardCopyOption.REPLACE_EXISTING);


            return  new GameStoreVo<>(200,"提交成功",null);
        } catch (Exception e) {
             throw new RuntimeException("操作失败，已触发TCC回滚", e); // 抛出异常触发回滚



        }
    }
}
